package com.hanson.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.common.bean.AttrValueBean;
import com.hanson.common.bean.GoodsRuleItemBean;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.GoodsAttrValueBean;
import com.hanson.entity.GoodsRuleBean;
import com.hanson.mapper.GoodsAttrValueBeanMapper;
import com.hanson.mapper.GoodsRuleBeanMapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class GoodsRuleService {
    @Autowired
    private GoodsRuleBeanMapper goodsRuleBeanMapper;
    @Autowired
    private GoodsAttrValueBeanMapper goodsAttrValueBeanMapper;

    /**
     * 根据属性进行排列组合
     *
     * @param list
     */
    public JSONObject generate(List<GoodsRuleItemBean> list,String id,String value) {
        JSONObject jsonObject = new JSONObject();
        if (CollectionUtils.isNotEmpty(list)) {
            List<AttrValueBean> headerList = new ArrayList<>();
            List<Object[]> inList = new ArrayList<>();
            final int[] count = {1};
            list.stream().forEach(c -> {
                if (CollectionUtils.isNotEmpty(c.getDetail())) {
                    inList.add(c.getDetail().toArray());
                    headerList.add(new AttrValueBean(c.getValue(),"value"+ count[0]));
                }
                count[0]++;
            });
            headerList.add(new AttrValueBean("图片",80,"pic"));
            headerList.add(new AttrValueBean("VIP价格",120,"price"));
            headerList.add(new AttrValueBean("售价",100,"price"));
            headerList.add(new AttrValueBean("原价",100,"oldPrice"));
            headerList.add(new AttrValueBean("库存",100,"stock"));
            headerList.add(new AttrValueBean("操作",70,"action"));
            List<Map<String,Object>> attrList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(inList)) {
                List<Object[]> result = BusinessUtil.combination(inList, 0, null);
                if(StringUtils.isEmpty(value) || "0".equals(value)){
                    result.stream().forEach(c -> {
                        Map<String,Object> valueObj = new LinkedHashMap();
                        Map<String,String> detailObj = new LinkedHashMap();
                        for (int i = 0; i < c.length; i++) {
                            valueObj.put("value"+(i+1),String.valueOf(c[i]));
                            detailObj.put(list.get(i).getValue(),String.valueOf(c[i]));
                        }
                        valueObj.put("detail",detailObj);
                        valueObj.put("image","");
                        attrList.add(valueObj);
                    });
                }else{
                    List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsId(Integer.parseInt(id));
                    Map<String,String> tempMap = new HashMap<>();
                    goodsAttrValueBeanList.stream().forEach(c->{
                        tempMap.put(c.getSuk(),c.getDetail());
                    });
                    result.stream().forEach(c -> {
                        StringBuffer tempSb = new StringBuffer();
                        for (int i = 0; i < c.length; i++) {
                            tempSb.append(String.valueOf(c[i])).append(",");
                        }
                        String key = tempSb.substring(0,tempSb.length()-1).toString();
                        if(tempMap.containsKey(key)){
                            attrList.add(JSONObject.parseObject(tempMap.get(key),Feature.OrderedField));
                        }
                    });
                }
            }
            jsonObject.put("header",headerList);
            jsonObject.put("attrList",attrList);
        }
        return jsonObject;
    }

    public List<GoodsRuleBean> getAllRule() {
        return goodsRuleBeanMapper.selectAll();
    }

    public void addGoodsRule(GoodsRuleBean goodsRuleBean) {
        goodsRuleBean.setCreateDate(new Date());
        if (CollectionUtils.isNotEmpty(goodsRuleBean.getRuleItem())) {
            goodsRuleBean.setRuleValue(JSON.toJSONString(goodsRuleBean.getRuleItem()));
        }
        goodsRuleBeanMapper.insert(goodsRuleBean);
    }

    public void modifyGoodsRule(GoodsRuleBean goodsRuleBean) {
        GoodsRuleBean returnBean = goodsRuleBeanMapper.selectByPrimaryKey(goodsRuleBean.getId());
        if (null != returnBean) {
            goodsRuleBean.setCreateDate(returnBean.getCreateDate());
            goodsRuleBean.setUpdateDate(new Date());
            if (CollectionUtils.isNotEmpty(goodsRuleBean.getRuleItem())) {
                goodsRuleBean.setRuleValue(JSON.toJSONString(goodsRuleBean.getRuleItem()));
            }
            goodsRuleBeanMapper.updateByPrimaryKey(goodsRuleBean);
        }
    }

    public void deleteGoodsRule(Integer id) {
        goodsRuleBeanMapper.deleteByPrimaryKey(id);
    }

    public GoodsRuleBean detailGoodsRule(Integer id) {
        return goodsRuleBeanMapper.selectByPrimaryKey(id);
    }

    public Page<GoodsRuleBean> listGoodsRule(Page<GoodsRuleBean> page, GoodsRuleBean goodsRuleBean) {
        List<GoodsRuleBean> list = goodsRuleBeanMapper.listGoodsRule(page, goodsRuleBean);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(c -> {
                if (StringUtils.isNotEmpty(c.getRuleValue())) {
                    List<GoodsRuleItemBean> itemList = JSONObject.parseArray(c.getRuleValue(), GoodsRuleItemBean.class);
                    StringBuffer specNameBuffer = new StringBuffer();
                    StringBuffer attrNameBuffer = new StringBuffer();
                    itemList.stream().forEach(a -> {
                        specNameBuffer.append(a.getValue()).append(",");
                        attrNameBuffer.append(a.getDetail()).append(",");
                    });
                    c.setSpecNames(specNameBuffer.substring(0, specNameBuffer.length() - 1).toString());
                    c.setAttrNames(attrNameBuffer.substring(0, attrNameBuffer.length() - 1).toString());
                }
            });
        }
        return page.setRecords(list);
    }
}
